<template>
  <div>
    <el-row type="flex" justify="end" class="button-save">
      <el-button type="primary" @click="save">保存</el-button>
    </el-row>
    <el-form
      ref="complainedForm"
      :model="complainedSymptom"
      :class="required == '1' ? 'require' : 'notRequire'"
      label-position="right"
      label-width="120px"
      size="small"
      class="complaint"
      :rules="complainRules"
    >
      <el-form-item label="主诉" prop="chiefComplaint">
        <el-input
          v-model="complainedSymptom.chiefComplaint"
          @input="chiefButton('chiefComplaint', 'chiefList')"
        />
      </el-form-item>
      <el-row class="button-row">
        <el-button
          v-for="(chief, index) in chiefList"
          :key="index"
          :class="[
            'chief-button',
            chief.flag ? 'is-active' : '',
            index === 0 ? 'chief-button-one' : ''
          ]"
          round
          @click="handleChief(index, 'chiefComplaint', 'chiefList')"
        >
          {{ chief.name }}
        </el-button>
      </el-row>
      <el-form-item label="过敏史" prop="allergySelect">
        <el-select
          v-model="complainedSymptom.allergySelect"
          style="width: 100%"
          multiple
          @change="handleSelect('allergyHistory', 'allergySelect')"
        >
          <el-option
            v-for="(allergy, index) in allergyList"
            :key="index"
            :value="allergy"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="hasOther('allergySelect')">
        <el-input
          type="textarea"
          v-model="complainedSymptom.allergyHistoryOther"
          resize="none"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="既往史" prop="previousSelect">
        <el-select
          v-model="complainedSymptom.previousSelect"
          style="width: 100%"
          multiple
          @change="handleSelect('previousIllness', 'previousSelect')"
        >
          <el-option
            v-for="(previous, index) in previousList"
            :key="index"
            :value="previous"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="hasOther('previousSelect')">
        <el-input
          type="textarea"
          v-model="complainedSymptom.previousIllnessOther"
          resize="none"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="急症类型" prop="emergencySelect">
        <el-select
          v-model="complainedSymptom.emergencySelect"
          style="width: 100%"
          multiple
          @change="handleSelect('emergencyType', 'emergencySelect')"
        >
          <el-option
            v-for="(emergency, index) in emergencyList"
            :key="index"
            :value="emergency"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="hasOther('emergencySelect')">
        <el-input
          type="textarea"
          v-model="complainedSymptom.emergencyTypeOther"
          resize="none"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="complainedSymptom.remark"
          @input="chiefButton('remark', 'remarksList')"
        />
      </el-form-item>
      <el-row class="button-row">
        <el-button
          v-for="(remark, index) in remarksList"
          :key="index"
          :class="['chief-button', remark.flag ? 'is-active' : '']"
          round
          @click="handleChief(index, 'remark', 'remarksList')"
        >
          {{ chief.name }}
        </el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  selectTriageDiseaseHistories,
  saveTriageDiseaseHistories,
  updateTriageDiseaseHistories
} from '@/api/triage/triage-new'
import { findHistoryManage } from '@/api/back-management/triage-manage/medicalHistory_management'
export default {
  name: 'TrageComplaint',
  props: {
    id: {
      type: Object,
      default: () => {}
    },
    require: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      complainedSymptom: {
        chiefComplaint: '',
        allergySelect: [],
        previousSelect: [],
        emergencySelect: []
      },
      required: '',
      chiefList: [],
      allergyList: [],
      previousList: [],
      emergencyList: [],
      remarksList: [],
      manage: [
        {
          resField: 'onUseMainSuit',
          prop: 'chiefList',
          label: 'name',
          flag: true
        },
        {
          resField: 'onUseAllergies',
          prop: 'allergyList',
          flag: false
        },
        {
          resField: 'onUsePastHistory',
          prop: 'previousList',
          flag: false
        },
        {
          resField: 'onUseEmergencyType',
          prop: 'emergencyList',
          flag: false
        },
        {
          resField: 'onUseRemarks',
          prop: 'remarksList',
          label: 'name',
          flag: true
        }
      ],
      complainRules: {
        chiefComplaint: null,
        allergySelect: null,
        previousSelect: null,
        emergencySelect: null,
        remark: null
      }
    }
  },
  created() {
    this.findHistoryManage()
    this.setRequire()
  },
  methods: {
    setRequire() {
      if (this.require.length > 0) {
        this.required = this.require[0].value
        if (this.required !== '2') {
          Object.keys(this.complainRules).forEach((el) => {
            this.complainRules[el] = [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          })
        } else {
          Object.keys(this.complainRules).forEach((el) => {
            this.complainRules[el] = null
          })
        }
      }
    },
    findHistoryManage() {
      findHistoryManage({
        hospitalId: this.$store.getters.hospitalId
      }).then((res) => {
        if (res.code == 0 && res.data.length > 0) {
          let obj = res.data[0]
          this.manage.forEach((item) => {
            if (obj[item.resField]) {
              let arr = []
              arr = obj[item.resField].split('<;>')
              arr.forEach((el) => {
                if (item.flag) {
                  let obj = {}
                  obj[item.label] = el
                  obj.flag = false
                  this[item.prop].push(obj)
                } else {
                  this[item.prop].push(el)
                }
              })
            }
          })

          this.selectTriageDisease(this.id.dispatchId)
        }
      })
    },
    selectTriageDisease(id) {
      if (id) {
        selectTriageDiseaseHistories({
          dispatchId: id,
          userId: this.$store.getters.userId,
          pageNum: 1,
          pageSize: 0
        }).then((res) => {
          if (res.code === 0) {
            if (res.data.list.length > 0) {
              this.complainedSymptom = res.data.list[0]
              this.setSelect()
              this.chiefButton('chiefComplaint', 'chiefList')
            }
          }
        })
      }
    },
    setSelect() {
      this.$set(this.complainedSymptom, 'allergySelect', [])
      this.$set(this.complainedSymptom, 'previousSelect', [])
      this.$set(this.complainedSymptom, 'emergencySelect', [])
      if (this.complainedSymptom.allergyHistory) {
        this.$set(
          this.complainedSymptom,
          'allergySelect',
          this.complainedSymptom.allergyHistory.split(',')
        )
      }
      if (this.complainedSymptom.previousIllness) {
        this.$set(
          this.complainedSymptom,
          'previousSelect',
          this.complainedSymptom.previousIllness.split(',')
        )
      }
      if (this.complainedSymptom.emergencyType) {
        this.$set(
          this.complainedSymptom,
          'emergencySelect',
          this.complainedSymptom.emergencyType.split(',')
        )
      }
    },
    handleSelect(field, select) {
      this.complainedSymptom[field] = this.complainedSymptom[select].join(',')
    },
    hasOther(select) {
      let i = this.complainedSymptom[select].indexOf('其他')
      if (i > -1) {
        return true
      } else {
        return false
      }
    },
    save() {
      this.$nextTick(() => {
        this.$refs.complainedForm.validate((valid) => {
          if (!valid && this.required == '1') {
            this.$message.error('请通过验证')
          } else {
            this.complainedSymptom.dispatchId = this.id.dispatchId
            this.complainedSymptom.medicalId = this.id.medicalId
            this.complainedSymptom.userId = this.$store.getters.userId
            if (!this.complainedSymptom.id) {
              this.add()
            } else {
              this.edit()
            }
          }
        })
      })
    },
    add() {
      saveTriageDiseaseHistories(this.complainedSymptom).then((res) => {
        if (res.code === 0) {
          this.$message.success('保存成功')
          this.selectTriageDisease(this.id.dispatchId)
        } else {
          this.$message.success('保存失败')
        }
      })
    },
    edit() {
      updateTriageDiseaseHistories(this.complainedSymptom).then((res) => {
        if (res.code === 0) {
          this.$message.success('保存成功')
          this.selectTriageDisease(this.id.dispatchId)
        } else {
          this.$message.success('保存失败')
        }
      })
    },
    handleChief(index, field, list) {
      if (this.complainedSymptom[field]) {
        let chief = this.complainedSymptom[field]
        let arr = chief.replace(/(^\s*)|(\s*$)/g, '').split(' ')
        let i = arr.indexOf(this[list][index].name)
        if (i > -1) {
          arr.splice(i, 1)
        } else {
          arr.push(this[list][index].name)
        }
        this.complainedSymptom[field] = arr.join(' ') + ' '
      } else {
        this.complainedSymptom[field] = this[list][index].name + ' '
      }
      this.chiefButton(field, list)
    },
    chiefButton(field, list) {
      let chief = this.complainedSymptom[field]
      let arr = chief.split(' ')
      this[list].forEach((item) => {
        let j = arr.indexOf(item.name)
        if (j > -1) {
          item.flag = true
        } else {
          item.flag = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.complaint {
  padding-right: 240px;
  .el-form-item--small.el-form-item {
    margin-bottom: 22px;
  }
  .button-row {
    padding: 0 240px 12px 120px;
    .chief-button-one{
      margin-left: 10px;
    }
    .chief-button {
      padding: 7px 20px;
      margin-bottom: 10px;
      &:hover,
      &:focus {
        color: #606266;
        border-color: #dcdfe6;
        background-color: #fff;
      }
    }
    .is-active {
      color: #13c2c2 !important;
      border-color: #b8eded !important;
      background-color: #e7f9f9 !important;
    }
  }
}

.button-save {
  padding-right: 40px;
  margin-bottom: 20px;
}
</style>

<style lang="scss">
.notRequire {
  .el-form-item.is-error .el-input__inner {
    border-color: #dcdfe6;
  }
}
</style>